<script setup lang="ts">
import type { ImagePreviewProps } from './types';

import { computed, ref } from 'vue';

import { spliceSeparator, spliceUrlPrefix } from '#/utils';

const props = withDefaults(defineProps<ImagePreviewProps>(), {
  imageUrls: () => [],
  separator: '|',
  previewWidth: 30,
  previewHeight: 30,
});

const visible = ref(false);

// 统一处理图片资源为标准化数组
const normalizedUrls = computed(() => {
  if (!props.imageUrls) return [];

  // 统一转换为字符串数组
  const source =
    typeof props.imageUrls === 'string'
      ? spliceSeparator(props.imageUrls, props.separator)
      : [...props.imageUrls];

  return source
    .map((item) => {
      // 处理可能的嵌套字符串结构
      const strItem = String(item).trim();
      return strItem ? spliceUrlPrefix(strItem) : null;
    })
    .filter(Boolean) as string[]; // 类型断言过滤空值
});

// 首图计算属性
const firstImage = computed(() => normalizedUrls.value[0] || '');
</script>

<template>
  <!-- 缩略图预览 -->
  <a-image
    :preview="{ visible: false }"
    :width="props.previewWidth"
    :height="props.previewHeight"
    :src="firstImage"
    @click="visible = true"
  />

  <!-- 隐藏的预览图集 -->
  <div style="display: none">
    <a-image-preview-group
      :preview="{
        visible,
        onVisibleChange: (vis) => (visible = vis),
      }"
    >
      <a-image
        v-for="(url, index) in normalizedUrls"
        :key="`preview-${index}`"
        :src="url"
      />
    </a-image-preview-group>
  </div>
</template>
